/**
 * request
 * @author Blurryface
 */

import SYS_CONFIG from '/utils/config'; 		// 配置类
import cryptoUtils from '/utils/CryptoJS';

// 全局状态globalData
import { storeToRefs } from "pinia";
import { useGlobalDataStore } from '@/globalData.js';

const errorCodeMap = {
    400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
    401: '用户没有权限（令牌、用户名、密码错误）。',
    403: '用户得到授权，但是访问是被禁止的。',
    404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
    406: '请求的格式不可得。',
    410: '请求的资源被永久删除，且不会再得到的。',
    422: '当创建一个对象时，发生一个验证错误。',
    500: '服务器发生错误，请检查服务器。',
    502: '网关错误。',
    503: '服务不可用，服务器暂时过载或维护。',
    504: '网关超时。'
}

// 加密
const encryptData = (data) => {
	// 全局状态globalData
	const { globalData } = storeToRefs(useGlobalDataStore())
	
    const ts = Date.now();
    const TsAndData = { ts, ...data };
	const visit_data = globalData.value.VISIT_DATA;
    const visit_id = visit_data.visit_id;
    // const visit_key = visit_data.visit_key;
	const encrypted_pwd_info = globalData.value.ENCRYPTED_PWD_INFO;
    const aes_key = encrypted_pwd_info.AES_KEY;
    const aes_iv = encrypted_pwd_info.AES_IV;
    const enParams = cryptoUtils.AES_Encrypt(TsAndData, aes_key, aes_iv);
    return {
        visit_id : visit_id,
        enparams : enParams,
        ts : ts,
    };
}

// 解密
const decryptData = (data) => {
	// 全局状态globalData
	const { globalData } = storeToRefs(useGlobalDataStore());
	
	const encrypted_pwd_info = globalData.value.ENCRYPTED_PWD_INFO;
    const aes_key = encrypted_pwd_info.AES_KEY;
    const aes_iv = encrypted_pwd_info.AES_IV;
    return cryptoUtils.AES_Decrypt(data, aes_key, aes_iv);
}

// 根据是否为公网选择基础 URL
function getBaseURL(domainType) {
    const networkConfig = SYS_CONFIG.isPublicNetwork ? SYS_CONFIG.publicNetwork : SYS_CONFIG.privateNetwork;
    if (domainType === 'HSYII') {
        return networkConfig.HSYIIDomain;
    } else if (domainType === 'GF') {
        return networkConfig.GFDomain;
    }
}

// 请求拦截器
const requestInterceptors = [];
// 响应拦截器
const responseInterceptors = [];
// 添加请求拦截器
function addRequestInterceptor(interceptor) {
    requestInterceptors.push(interceptor);
}
// 添加响应拦截器
function addResponseInterceptor(interceptor) {
    responseInterceptors.push(interceptor);
}
// 执行请求拦截器
function executeRequestInterceptors(config) {
    let newConfig = { ...config };
    requestInterceptors.forEach((interceptor) => {
        newConfig = interceptor(newConfig);
    });
    return newConfig;
}
// 执行响应拦截器
function executeResponseInterceptors(response) {
    let newResponse = { ...response };
    responseInterceptors.forEach((interceptor) => {
        newResponse = interceptor(newResponse);
    });
    return newResponse;
}

// 初始化拦截器
function setupInterceptors() {
    // request 请求拦截器
    addRequestInterceptor((config) => {
        const { data, encrypt, action } = config;
        // console.log('Request Content : ', config);
        if (encrypt) { // request 拦截并加密
            // console.log('开始加密')
            const encryptedData = encryptData(data)
            config.data = {...encryptedData, action}

            // console.log('Request Content After Encrypt: ', config);
        } else {
            config.data = {...data, action}
        }
        config.header = {
            'Content-Type': 'application/x-www-form-urlencoded',
            ...config.header
        };
        return config;
    });

    // 响应拦截器
    addResponseInterceptor((response) => {
        const { encrypt } = response.config;
        // console.log('Response Content : ', response);
        let responseData = response.data;
        if (encrypt) { // response 拦截并解密
            // console.log('开始解密')
            if (responseData && responseData.endata) {
                responseData = decryptData(responseData.endata);
            } else {
                console.error('响应数据结构不符合预期，无法解密');
            }

            // console.log('Response Content After decrypt: ', response);
        }
        response.data = responseData;
        return response;
    });
}

// 发起请求
function sendRequest(config) {
    const newConfig = executeRequestInterceptors(config);
    return new Promise((resolve, reject) => {
        uni.request({
            url: getBaseURL(newConfig.domainType) + newConfig.url,
            method: newConfig.method,
            data: newConfig.data,
            header: newConfig.header,
            timeout: newConfig.timeout || 6000,
            success: (res) => {
                const newRes = executeResponseInterceptors({ ...res, config: newConfig });
                resolve(newRes.data);
            },
            fail: (err) => {
                const status = err.statusCode || null;
                const message = status ? errorCodeMap[status] || '未知错误' : '网络错误';
                console.error(`uni.request fail: ${status}:  ${message}`, err);
                reject({ status, message });
            }
        });
    });
}

// 初始化拦截器
setupInterceptors();

/**
 * HSYIIRequest HSYII后台请求
 * @param apiUrl ControllerName + actionName
 * @param data 参数。根据 encrypt 判定是否需要加密
 * @param method
 * @param encrypt
 * @param options
 * @returns {Promise<unknown>}
 * @constructor
 */
export const HSYIIRequest = (apiUrl, data = {}, method = 'post', encrypt = false, options = {}) => {
    const config = {
        url: apiUrl,
        data,
        method,
        encrypt,
        domainType: 'HSYII',
        ...options
    };
    return sendRequest(config);
};

/**
 * GFRequest，另一后台请求
 * @param params 无需加密的参数对象，{ c,  a,  action }
 * @param data 根据 encrypt 判定是否需要加密
 * @param method
 * @param encrypt
 * @param options
 * @returns {Promise<unknown>}
 * @constructor
 */
export const GFRequest = (params, data = {}, method = 'post', encrypt = false, options = {}) => {
    const {c, a, action} = params
    const apiUrl = `?c=${c}&a=${a}`
    const config = {
        url: apiUrl,
        data,
        method,
        encrypt,
        action,
        domainType: 'GF',
        ...options
    };
    return sendRequest(config);
};

